package com.hibase.core.bireport.service.bi.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hibase.common.exception.HibaseAssert;
import com.hibase.core.bireport.entity.BiReportSearchVo;
import com.hibase.core.bireport.entity.bi.WmsBiConfig;
import com.hibase.core.bireport.service.bi.BiConfigService;
import com.hibase.core.bireport.service.bi.BiService;
import com.hibase.core.bireport.util.BiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author chenfeng
 * @version 1.0
 * @date 2021/11/8 11:10
 * @des https://gitee.com/cheershi
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class,readOnly = true)
public class BiServiceImpl implements BiService {

    @Value("${hibase.fineReport.enableJwt: false}")
    private Boolean enableJwt;

    @Value("${hibase.fineReport.validTime: 1800000}")
    private Long validTime;


    @Value("${hibase.fineReport.sign: hichain}")
    private String sign;
    
    @Autowired
    private BiConfigService wmsBiConfigService;

    @Override
    public String getReportUrl(BiReportSearchVo searchVO) {
        if(log.isDebugEnabled()){
            log.debug("【BI-Report】 type : {} ; id : {}", searchVO.getType(), searchVO.getId());
        }
        WmsBiConfig biConfig = wmsBiConfigService.getOne(Wrappers.<WmsBiConfig>lambdaQuery()
                .eq(WmsBiConfig::getTypeCode, searchVO.getType())
        );
        HibaseAssert.notNull(biConfig,"未找到BI配置: {}",searchVO.getType());
        String url = biConfig.getBiUrl();
        String path = StrUtil.subAfter(url,"viewlet=",true);
        if (StrUtil.isNotBlank(url)&&StrUtil.isNotBlank(searchVO.getId())){
            url = url.concat("&id=").concat(searchVO.getId());
        }
        if (CollUtil.isNotEmpty(searchVO.getIds())){
            String ids = CollUtil.join(searchVO.getIds(), ",", "'", "'");
            url = url.concat("&ids=").concat(ids);
        }
        if (enableJwt){
            String jwtToken = BiUtil.createJwt("", "", path, validTime, sign);
            url = url.concat("&fine_digital_signature=").concat(jwtToken);
        }

        log.info("【BI-Report】 resultURL : {}",url);
        return url;
    }

}
